#include <QtGui/QAction>
#include <QtGui>
#include <QHBoxLayout>
#include "qtpropertybrowser.h"
#include "qteditorfactory.h"
#include "qttreepropertybrowser.h"
#include "qtpropertymanager.h"
#include "qtvariantproperty.h"
#include "qttreepropertybrowser.h"
#include "improfilewidget.h"
#include "ImProfileControl.h"

ImProfileWidget::ImProfileWidget(QWidget *parent)
: QWidget(parent)
{
	QHBoxLayout *mainLayout = new QHBoxLayout;
	m_profileCtrl = new ImProfileControl(this);
	m_profileCtrl->loadTemplate("profiles");
	qDebug("file has %d elements", m_profileCtrl->m_elementList.count());

	m_profileCombox = new QComboBox(this);
	m_groupCombox = new QComboBox(this);
	connect(m_profileCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(profileChange(int)) );
	connect(m_groupCombox, SIGNAL(currentIndexChanged ( const QString &) ), 
					 this, SLOT(initProfileByGroup(const QString &)) );

	QVBoxLayout *profileLayout = new QVBoxLayout;
	profileLayout->addWidget(m_groupCombox);
	profileLayout->addWidget(m_profileCombox);
	mainLayout->addLayout(profileLayout);
	mainLayout->addWidget(m_profileCtrl);
	setLayout(mainLayout);
	this->setFixedSize(600, 660);
	init();
}

ImProfileWidget::~ImProfileWidget()
{
	delete m_profileCtrl;
}

void ImProfileWidget::init()
{
	initGroup();
	initProfile();
}

void ImProfileWidget::initGroup()
{
	for( int i=0; i<m_profileCtrl->m_groupList.count(); i++)
	{
		ProfileGroup *item = m_profileCtrl->m_groupList.at(i);
		m_groupCombox->addItem(item->name);
		m_groupCombox->setItemData(-1, item->text);
	}
}

void ImProfileWidget::initProfile()
{
	for( int i=0; i<m_profileCtrl->m_profileList.count(); i++)
	{
		ProfileItem *item = m_profileCtrl->m_profileList.at(i);
		m_profileCombox->addItem(item->id);
		m_profileCombox->setItemData(m_profileCombox->count()-1, item->url);
	}
}

void ImProfileWidget::initProfileByGroup(const QString &groupName)
{
	m_profileCombox->clear();
	for( int i=0; i<m_profileCtrl->m_profileList.count(); i++)
	{
		ProfileItem *item = m_profileCtrl->m_profileList.at(i);
		if (item->group->name == groupName)
		{
			m_profileCombox->addItem(item->id);
			m_profileCombox->setItemData(m_profileCombox->count()-1, item->url);
		}		
	}
}



void ImProfileWidget::profileChange(int index)
{
	QString url = m_profileCombox->itemData(index).toString();
	if (!url.isEmpty())
	{
		qDebug() << "profileUrl" << url;
		m_profileCtrl->templateParse(url);

		PropertyItem *pItem;
		QString _key = "input_time_offset";
		if (m_profileCtrl->findItemData(_key, pItem))
		{
			pItem->item->setValue("123456");
			pItem->value = "123456";
			m_profileCtrl->valueUpdate(pItem->key, "123456");
			m_profileCtrl->displayData();
		}
	}	
}